import logging
from pathos.multiprocessing import ProcessingPool as Pool
from datetime import datetime
from django.conf import settings
from django.core.management import BaseCommand
from event_rule.rule_config import RULE_CONFIG
from common.es_core.base_report_creator import aggregate_data
from common.const import IntervalType

_LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):
    def __init__(self):
        super(Command, self).__init__()
        self.index_list = settings.DWC_INDEX + settings.CP_INDEX

    def add_arguments(self, parser):
        parser.add_argument('--interval_type', dest='interval_type', help='valid value: hour|day|week|month|total')
        parser.add_argument('--base_time', dest='base_time', help='yyyy-mm-dd HH:MM:SS')
        parser.add_argument('--last_window', dest='last_window', type=int, default=False,
                            help='current window or last window')

    def handle(self, **kwargs):
        pool = Pool(nodes=8)
        interval_type = kwargs['interval_type']
        base_time = kwargs['base_time']
        interval_type = IntervalType(interval_type) if interval_type else IntervalType.HOUR
        last_window = kwargs['last_window'] or 0
        base_time = datetime.strptime(base_time, '%Y-%m-%d %H:%M:%S') if base_time else datetime.now()
        start_window = 0
        if not last_window:
            if interval_type == IntervalType.HOUR or interval_type == IntervalType.DAY and datetime.now().hour == 0:
                start_window, _last_window = 1, 1
            else:
                start_window, _last_window = 0, 0
        else:
            _last_window = last_window
        for index in self.index_list:
            for window in range(start_window, _last_window + 1):
                rule_config = RULE_CONFIG.get(index, {})
                for key, config in rule_config.items():
                    if 'rule' not in config:
                        continue
                    print(index, key, index)
                    pool.apipe(aggregate_data, interval_type, config, index, base_time, window)
        pool.close()
        pool.join()
